package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchOrderNodeService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.client.vo.batch.WorksheetMergeVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.BatchAcceptOrderInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptDetailMapper;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;

/**
 * @author lyx
 * @version V1.0
 * @Description:
 * @date 2021/11/26
 * @Package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module
 */
@Service
public class BatchAcceptOrderListModuleHandler extends AbstractModuleHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Autowired
    private IBatchOrderNodeService batchOrderNodeService;

    @Autowired
    private IUnicomRegionService unicomRegionService;

    @Autowired
    private KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {
        SceneNewOfferSeneVO sceneOrderListInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        BatchAcceptOrderInfoVO batchAcceptOrderInfoVO = new BatchAcceptOrderInfoVO();
        KiteSceneInst sceneInst = this.querySceneInstService.getSceneInst(sceneInstId);

        setTitleAttr(sceneInstId, batchAcceptOrderInfoVO);
        Map<String, Object> orderInfo = querySceneInstService.getExtParameterValue(sceneInstId, "batchOrderInfo");
        List<Map<String, Object>> subOrderList = KiteMapUtils.getValue(orderInfo, "workSheetData");
        if (Objects.isNull(subOrderList) || subOrderList.isEmpty()) {
            sceneOrderListInfoVo.setBatchAcceptOrderInfoVO(batchAcceptOrderInfoVO);
            return Collections.singletonList(batchAcceptOrderInfoVO);
        }
        List<WorksheetMergeVO> worksheetMergeList = getWorksheetMergeVOList(sceneInst, subOrderList);
        batchAcceptOrderInfoVO.setOrderList(worksheetMergeList);
        if (KiteStringUtils.equals("batchOrderStartRent",
            querySceneInstService.getExtParameterValue(sceneInstId, "preTaskCode"))) {
            batchAcceptOrderInfoVO.setCheckBox(true);
        }
        sceneOrderListInfoVo.setBatchAcceptOrderInfoVO(batchAcceptOrderInfoVO);
        return Collections.singletonList(batchAcceptOrderInfoVO);
    }

    private List<WorksheetMergeVO> getWorksheetMergeVOList(KiteSceneInst sceneInst, List<Map<String, Object>> subOrderList) {
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId());
        String cateName = offerInst.getAttrValue("cateName");
        List<WorksheetMergeVO> worksheetMergeList = subOrderList.stream().map(subOrder -> {
            WorksheetMergeVO worksheetMerge = KiteMapUtils.mapToBean(subOrder, WorksheetMergeVO.class);
            if (Objects.isNull(worksheetMerge)) {

                return null;
            }
            String provinceCode = KiteMapUtils.getString(subOrder, "provinceCode");
            String cityCode = KiteMapUtils.getString(subOrder, "cityCode");
            String districtCode = KiteMapUtils.getString(subOrder, "districtCode");
            // 省
            List<UnicomRegion> provinceList = unicomRegionService.subRegionFromPlatform(new UnicomRegionQry());
            String provinceName =
                provinceList.stream().filter(p -> KiteStringUtils.equals(p.getRegionCode(), provinceCode)).findFirst()
                    .map(UnicomRegion::getRegionName).orElse("");
            // 市
            List<UnicomRegion> cityList =
                unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(provinceCode, "20"));
            String cityName = cityList.stream().filter(p -> KiteStringUtils.equals(p.getRegionCode(), cityCode))
                .findFirst().map(UnicomRegion::getRegionName).orElse("");
            // 区
            List<UnicomRegion> areaList =
                unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(cityCode, "30"));
            String areaName = areaList.stream().filter(p -> KiteStringUtils.equals(p.getRegionCode(), districtCode))
                .findFirst().map(UnicomRegion::getRegionName).orElse("");
            String regionValDesc = String.join(SymbolConsts.HYPHEN, provinceName, cityName, areaName);
            worksheetMerge.setUserLocationName(regionValDesc);
            worksheetMerge.setCatagoryName(cateName);
            worksheetMerge.setNodeName(KiteMapUtils.getString(subOrder, "nodeCode"));
            return worksheetMerge;
        }).collect(Collectors.toList());
        return worksheetMergeList;
    }

    private void setTitleAttr(String sceneInstId, BatchAcceptOrderInfoVO batchAcceptOrderInfoVO) {
        List<CommonAttrVO> titleCommonAttrs = Lists.newArrayList();
        packageCommonAttr(titleCommonAttrs, "orderId", "订单编号", "D");
        packageCommonAttr(titleCommonAttrs, "serialNumber", "业务号码", "D");
        packageCommonAttr(titleCommonAttrs, "catagoryName", "商品分类", "D");
        packageCommonAttr(titleCommonAttrs, "goodsName", "商品名称", "D");
        packageCommonAttr(titleCommonAttrs, "nodeName", "订单环节", "D");
        packageCommonAttr(titleCommonAttrs, "taskName", "任务名称", "D");
        packageCommonAttr(titleCommonAttrs, "userLocationName", "用户归属", "D");
        packageCommonAttr(titleCommonAttrs, "flowId", "工单编号", "H");
        batchAcceptOrderInfoVO.setTitleAttr(titleCommonAttrs);
    }

    private void packageCommonAttr(List<CommonAttrVO> titleCommonAttrs, String fieldName, String cname, String showType) {
        CommonAttrVO commonAttrVO = new CommonAttrVO();
        commonAttrVO.setCname(cname);
        commonAttrVO.setFieldName(fieldName);
        commonAttrVO.setShowType(showType);
        titleCommonAttrs.add(commonAttrVO);
    }

    @Override
    public List<? extends ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        SceneNewOfferSeneVO sceneOrderListInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        BatchAcceptOrderInfoVO batchAcceptOrderInfoVO = new BatchAcceptOrderInfoVO();

        KiteSceneInst sceneInst = this.querySceneInstService.getSceneInst(sceneInstId);
        setTitleAttr(sceneInstId, batchAcceptOrderInfoVO);
        Long batchNodeId = querySceneInstService.getExtParameterValue(sceneInstId, "batchNodeId");
        if (Objects.isNull(batchNodeId)) {
            return Collections.singletonList(batchAcceptOrderInfoVO);
        }
        List<KiteBatchAcceptDetail> failDetails =
            kiteBatchAcceptDetailMapper.select(new KiteBatchAcceptDetail().setBatchId(batchNodeId).setStatusCd("1100"));
        if (KiteListUtils.isEmpty(failDetails)) {
            return Collections.singletonList(batchAcceptOrderInfoVO);
        }
        List<Map<String, Object>> subOrderList = failDetails.stream()
            .map(failDetail -> JSONObject.parseObject(failDetail.getAttrJson())).collect(Collectors.toList());
        List<WorksheetMergeVO> worksheetMergeList = getWorksheetMergeVOList(sceneInst, subOrderList);
        batchAcceptOrderInfoVO.setOrderList(worksheetMergeList);
        batchAcceptOrderInfoVO.setCheckBox(false);
        batchAcceptOrderInfoVO.setIsEdit(KeyConsts.IFTRUE_F);
        sceneOrderListInfoVo.setBatchAcceptOrderInfoVO(batchAcceptOrderInfoVO);
        return Collections.singletonList(batchAcceptOrderInfoVO);
    }
}
